﻿using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Mvc;

namespace CodeStash.Filters
{
    public class JSONInputAttribute : ActionFilterAttribute
    {
        public string Param { get; set; }

        public Type RootType { get; set; }

        private Encoding GetEncoding(string contentType)
        {
            Encoding encoding = Encoding.Default;

            switch (contentType)
            {
                case "application/json; charset=UTF-7":
                    encoding= Encoding.UTF7;
                    break;
                case "application/json; charset=UTF-8":
                    encoding= Encoding.UTF8;
                    break;
                case "application/json; charset=unicode":
                    encoding= Encoding.Unicode;
                    break;
                case "application/json; charset=ascii":
                    encoding= Encoding.ASCII;
                    break;
            }

            return encoding;
        }


        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                string json = filterContext.HttpContext.Request.Form[Param];

                if (json == "[]" || json == "\",\"" || String.IsNullOrEmpty(json))
                {
                    filterContext.ActionParameters[Param] = null;
                }
                else
                {
                    Encoding encoding = GetEncoding(filterContext.HttpContext.Request.ContentType);

                    using (var ms = new MemoryStream(encoding.GetBytes(json)))
                    {
                        filterContext.ActionParameters[Param] = new DataContractJsonSerializer(RootType).ReadObject(ms);
                    }
                }
            }
            catch
            {
                filterContext.ActionParameters[Param] = null;
            }
        }

    }
}